<script setup>
import { ref, computed, onUnmounted } from 'vue'
import dayjs from 'dayjs'

const props = defineProps({
  initialTime: Number, // 初始倒计时时间（秒）
  orderId: Number
})
const emit = defineEmits(['finish'])
const time = ref(props.initialTime)
let timer = null

const formatTime = computed(() => {
  return dayjs.unix(time.value).format('mm分ss秒')
})

// 启动倒计时
const start = () => {
  timer = setInterval(() => {
    if (time.value > 0) {
      time.value--
    } else {
      clearInterval(timer)
        emit('finish',orderId)
    }
  }, 1000)
}

start() // 组件挂载时自动启动

// 组件卸载时清除定时器
onUnmounted(() => {
  clearInterval(timer)
})
</script>

<template>
  <span class="down-time">
    <i class="iconfont icon-down-time"></i>
    <b>付款截止: {{ formatTime }}</b>
  </span>
</template>